<template>
  <div>
      <!-- start tabs 选择 -->
      <div class="chart-meet-rate">
        <el-radio-group v-model="radioVal" @change="e=>handleChange('selectType',e)" size="mini">
            <el-radio-button label="0">地区</el-radio-button>
            <el-radio-button label="3">部门</el-radio-button>
            <el-radio-button label="4">人员</el-radio-button>
        </el-radio-group>
      </div>
      <!-- end tabs 选择 -->

      <div class="chart-meet-rate-select">
        <!-- start 地区 -->
        <el-select
            v-if="radioVal == '0'"
            key="addressType"
            :value="addressType"
            @change="e=>handleChange('addressType',e)"
            size="small"
        >
            <el-option
                v-for="item in selectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
        </el-select>

        <el-cascader
            v-show="radioVal == '0'"
            :value="areaCodeList"
            collapse-tags
            :options="cnareaList"
            :props="cnareaProps"
            clearable
            @change="e=>handleChange('areaCodeList',e)">
        </el-cascader>
        <!-- end 地区 -->

        <!-- start 部门 -->
        <biz-team-select
          class="team-select"
          v-if="radioVal == '3'"
          ref="teamSelect"
          :value="tags"
          collapse
          multiple
          size="small"
          is-auto-select-child
          :fetch-func="fetchTeam"
          @input="e=>handleChange('tags',e)"
        />
        <!-- end 部门 -->

        <!-- start 人员 -->
        <el-select
            v-if="radioVal == '4'"
            key="users"
            :value="users"
            clearable
            multiple
            collapse-tags
            size="small"
            placeholder="选择人员"
            filterable
            remote
            :remote-method="remoteMethod"
            @change="e=>handleChange('users',e)"
            v-el-select-loadmore="loadmoreOptions"
        >
            <el-option
                v-for="item in usersList"
                :key="item.userId"
                :label="item.displayName"
                :value="item.userId"
            >
                <template v-if="isOpenData">
                    <open-data type="userName" :openid="item.staffId || item.displayName"></open-data>
                </template>
            </el-option>
        </el-select>
        <!-- end 人员 -->
      </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue';
// api
import * as ReportApi from '@src/api/ReportApi';
import feLibCity from 'fe-lib-city';
import http from 'src/util/HttpUtil';
/* util */
import { isOpenData } from '@src/util/platform';
import _ from 'lodash';

export default {
    name: 'chart-stock-meet-rate-setting',
    props:{
        chartOption: {
            type: Object,
        },
    },
    computed:{
        addressType() {
            return this.chartOption?.addressType || '1';
        },
        areaCodeList() {
            return this.chartOption?.areaCodeList || [];
        },
        tags() {
            return this.chartOption?.tags || [];
        },
        users() {
            return this.chartOption?.users || [];
        },
    },
    setup(props, { emit }){
        // tabs
        const radioVal = ref('0');
        const chartOption = computed(() => {
			return props.chartOption;
		})
		watch(chartOption, (n,o) => {
            radioVal.value = chartOption.value?.selectType;
        })
        
        // 地址计算规则
        const selectList = ref([
            { label: '按照客户工单服务地址', value: '1' },
            { label: '按照服务团队负责区域', value: '2' },
        ]);       
        
        // 地区
        const areaCode = ref('0');
        const cnareaList = ref([]);
        // 区域地址数据
        const cnareaProps = ref({
          value: 'areaCode',
          label: 'name',
          multiple:true,
          checkStrictly: true,
          lazy: true,
          lazyLoad: async (node, resolve)=>{
            let { value, level } = node;

            areaCode.value = value || '0';
            const { data } = await getCnareaList(areaCode.value);
            const nodeData = data && data.map(x=>{
                return {
                    ...x,
                    leaf: Number(level) >= 2
                }
            })
            resolve(nodeData);
          }
        });
        // 获取省市区数据
        const getCnareaList = async (areaCode = '0') => {
            try {
                const result = await ReportApi.getCnareaList({ areaCode });

                if(areaCode == '0') return cnareaList.value = result.data || [];
                return result;
            } catch (error) {
                console.log('getCnareaList', error);
            }
        }

        // 人员
        const usersList = ref([]);
        const loading = ref(false);
        const pageNum = ref(1);
        const userName = ref('');
        const total = ref(0);
        // 获取人员信息
        const getUsersList = async (queryAll = true) => {
            try {
                loading.value = true;
                const { code, data, msg } = await ReportApi.getPcTeamUser({
                    queryAll, // 是否展示已删除
                    userName: userName.value,
                    pageSize: 10,
                    pageNum: pageNum.value
                });
                if(code !== 200) return;

                loading.value = false;
                total.value = data.totalCount;
                usersList.value = usersList.value.concat(data.baseUserDTOList);
            } catch (error) {
                console.log(error)
            }
        }

        // 人员搜索 start
        const remoteMethod = (query)=>{
            pageNum.value = 1;
            userName.value = query;
            usersList.value = []
            getUsersList();
        }
        const visibleHandler = (visible)=>{
            if (visible) return getUsersList();
        }

        // 人员分页
        const loadmore = _.debounce(() => {
            if(usersList.value.length === total.value) return;
            
            pageNum.value++;
            getUsersList();
        }, 50)

        const loadmoreOptions = reactive({
            disabled: false,
            callback: loadmore,
            distance: 10
        })
        // 人员搜索 end

        // 事件
        const handleChange = (type,val)=>{
            const newValue = {
                ...props.chartOption,
                page: 1,
                [type]: val
            }
            emit('fetchData', newValue, 'meetSelectType');
        }

        // 人员权限控制
        const fetchTeam = (params) => {
            return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW', source: 'dataInfo'}})
        }
        
        onMounted(()=>{
            getUsersList();
        })

        return {
            radioVal,
            selectList,
            usersList,
            cnareaProps,
            handleChange,
            cnareaList,
            fetchTeam,
            remoteMethod,
            visibleHandler,
            loading,
            loadmoreOptions,
        };
    }
}
</script>

<style lang="scss" scoepd>
.chart-meet-rate {
    text-align: center;
}
.chart-meet-rate-select {
    text-align: right;
    padding: 5px 0;
    .team-select {
        display: inline-block;
        max-width: 300px;
    }
}
</style>